<template>
  <div class="app-container">
    <div class="topSearch">
      <el-row>
        <el-button type="primary" @click="showDialog('add')">Add</el-button>
        <el-input v-model="logisticName" clearable placeholder="logistic name" />
        <el-date-picker
          v-model="rangeDate"
          class="myDatePicker"
          type="daterange"
          range-separator="to"
          start-placeholder="start date"
          end-placeholder="end date"
          value-format="yyyy-MM-dd"
        />
        <el-button type="primary" @click="searchData()">Search</el-button>
      </el-row>
    </div>

    <el-table v-loading="loading" :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="Logistics" />
      <el-table-column prop="shopify" label="Shopify Carrier" />
      <el-table-column prop="woocommerce" label="Woocommerce Carrier" />
      <el-table-column prop="createTime" label="Create Time" />
      <el-table-column label="operation" width="130">
        <template slot-scope="scope">
          <div>
            <el-button
              type="text"
              @click="showDialog('edit', scope.row.id)"
            >Edit</el-button>
            <el-button
              type="text"
              @click="deleteItem(scope.row.id)"
            >Delete</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="tableData.length"
      id="btmPagination"
      :class="{ open: sidebar }"
      :current-page="currentPage"
      :page-sizes="[10, 30, 50, 100, 200]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑物流弹窗 -->
    <el-dialog
      v-if="dialogFormVisible"
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="420px"
    >
      <div v-loading="editLoading">
        <el-form
          ref="ruleForm"
          :model="dialogForm"
          :rules="rules"
          :label-width="formLabelWidth"
        >
          <el-form-item prop="name" label="logistics">
            <el-input v-model="dialogForm.name" placeholder="logistics" />
          </el-form-item>
          <el-form-item v-if="dialogForm.isInputShopify" prop="inputShopify" label="shopify">
            <el-input v-model="dialogForm.inputShopify" class="input" placeholder="Logistics enquiry website" />
            <el-button
              type="text"
              style="margin-left: 10px;"
              @click="toggleEnterModel('shopify')"
            >other</el-button>
          </el-form-item>
          <el-form-item v-if="!dialogForm.isInputShopify" prop="shopify" label="shopify">
            <el-select
              v-model="dialogForm.shopify"
              placeholder="shopify carrier"
            >
              <el-option
                v-for="item in options['shopify']"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-button
              type="text"
              style="margin-left: 10px;"
              @click="toggleEnterModel('shopify')"
            >other</el-button>
          </el-form-item>
          <el-form-item v-if="dialogForm.isInputWooc" prop="inputWoocommerce" label="woocommerce">
            <el-input v-model="dialogForm.inputWoocommerce" class="input" placeholder="Logistics enquiry website" />
            <el-button
              type="text"
              style="margin-left: 10px;"
              @click="toggleEnterModel('woocommerce')"
            >other</el-button>
          </el-form-item>
          <el-form-item v-if="!dialogForm.isInputWooc" prop="woocommerce" label="woocommerce">
            <el-select
              v-model="dialogForm.woocommerce"
              placeholder="woocommerce carrier"
            >
              <el-option
                v-for="item in options['woocommerce']"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-button
              type="text"
              style="margin-left: 10px;"
              @click="toggleEnterModel('woocommerce')"
            >other</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button
            type="primary"
            @click="submitData('ruleForm')"
          >Confirm</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  logisticsAdd,
  logisticsPage,
  logisticsEdit,
  logisticsDelete,
  logisticsRead
} from '@/api/logistics';
import { postResult } from '@/utils/dataFormat';
import { validateSelect, validateField } from '@/utils/validate';
export default {
  data() {
    return {
      logisticName: '',
      rangeDate: '',
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      editLoading: false,
      dialogType: 'add',
      dialogForm: {
        inputShopify: false,
        inputWooc: false
      },
      rules: {
        name: [{ validator: (rule, value, callback) => validateField(rule, value, callback), required: true, trigger: 'blur' }],
        shopify: [validateSelect()],
        woocommerce: [validateSelect()],
        inputShopify: [{ required: true, validator: (rule, value, callback) => validateField(rule, value, callback), trigger: 'blur' }],
        inputWoocommerce: [{ required: true, validator: (rule, value, callback) => validateField(rule, value, callback), trigger: 'blur' }]
      },
      formLabelWidth: '130px',
      options: {
        shopify: [
          '4PX',
          'APC',
          'Amazon Logistics UK',
          'Amazon Logistics US',
          'Australia Post',
          'Bluedart',
          'Canada Post',
          'China Post',
          'DHL',
          'DHL eCommerce',
          'DHL eCommerce Asia',
          'Delhivery',
          'Eagle',
          'FSC',
          'FedEx',
          'FedEx UK',
          'GLS',
          'Globegistics',
          'Japan Post',
          'New Zealand Post',
          'PostNord',
          'Purolator',
          'Royal Mail',
          'Sagawa',
          'TNT',
          'TNT Post',
          'UPS',
          'USPS',
          'Yamato',
          'YunExpress',
          'Anjun Logistics'
        ],
        woocommerce: []
      }
    };
  },
  computed: {
    dialogTitle: function() {
      return this.dialogType === 'add'
        ? 'Add'
        : this.dialogType === 'edit'
          ? 'Edit'
          : '';
    },
    sidebar() {
      return this.$store.state.app.sidebar.opened;
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.loading = true;
      logisticsPage({
        beginCreateTime: this.rangeDate ? this.rangeDate[0] : '',
        endCreateTime: this.rangeDate ? this.rangeDate[1] : '',
        name: this.logisticName,
        pageNo: 1,
        pageSize: 10
      }).then((res) => {
        this.loading = false;
        this.tableData = res.data.data;
        this.total = res.data.totalCount;
      });
    },
    searchData() {
      this.currentPage = 1;
      this.init();
    },
    showDialog(type, id) {
      this.dialogType = type;
      if (type === 'add') {
        // 新增
        this.editLoading = false;
        this.dialogType = 'add';
        this.dialogForm = {
          isInputShopify: false,
          isInputWooc: false
        };
      } else if (type === 'edit') {
        // 编辑
        this.editLoading = true;
        logisticsRead(id).then((res) => {
          this.editLoading = false;
          const data = res.data;
          if (this.options['shopify'].indexOf(data['shopify']) === -1) {
            data['isInputShopify'] = true;
            data['inputShopify'] = data['shopify'];
          } else {
            data['isInputShopify'] = false;
          }
          if (this.options['woocommerce'].indexOf(data['woocommerce']) === -1) {
            data['isInputWooc'] = true;
            data['inputWoocommerce'] = data['woocommerce'];
          } else {
            data['isInputWooc'] = false;
          }
          this.dialogForm = data;
        });
      }
      this.dialogFormVisible = true;
    },
    toggleEnterModel(type) {
      if (type === 'shopify') {
        this.$refs.ruleForm.clearValidate(['shopify', 'inputShopify']);
        this.dialogForm.isInputShopify = !this.dialogForm.isInputShopify;
        this.dialogForm.shopify = '';
      } else {
        this.$refs.ruleForm.clearValidate(['woocommerce', 'inputWoocommerce']);
        this.dialogForm.woocommerce = '';
        this.dialogForm.isInputWooc = !this.dialogForm.isInputWooc;
      }
    },
    submitData(ruleForm) {
      this.$refs[ruleForm].validate(async(valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.dialogForm));
          if (params.isInputWooc) {
            params['woocommerce'] = params.inputWoocommerce;
            delete params.inputWoocommerce;
          }
          if (params.isInputShopify) {
            params['shopify'] = this.dialogForm.inputShopify;
            delete params.inputShopify;
          }
          if (this.dialogType === 'edit') {
            delete params.createTime;
            delete params.updateTime;
          }
          const httpUri =
            this.dialogType === 'add' ? logisticsAdd : logisticsEdit;
          httpUri(params).then((res) => {
            postResult(res, this.$message, this.init);
            if (res.code === 200) {
              this.dialogFormVisible = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    deleteItem(id) {
      this.$confirm(
        'This action will delete the data permanently. Do you want to continue?',
        'Hint',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          logisticsDelete([id]).then((res) => {
            postResult(res, this.$message, this.init);
          });
        })
        .catch(() => {
          this.$message.info('undeleted');
        });
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.init();
    }
  }
};
</script>
<style lang="scss" scoped>
.thumbnailUri {
  >>> .el-form-item__content {
    min-width: 150px;
  }
}
.title {
  background: #f6f6f6;
  height: 32px;
  line-height: 32px;
  padding: 0 20px 0 10px;
  margin-bottom: 15px;
  .el-button {
    float: right;
  }
}
.tip {
  text-align: center;
  font-size: 13px;
  color: #848484;
}
.variantItem {
  display: flex;
  border-top: 1px solid #ddd;
  padding-top: 10px;
  margin-top: -15px;
  .leftArea {
    flex: 1;
  }
  .rightArea {
    width: 50px;
    text-align: center;
  }
}
.dialog-footer {
  padding: 20px 0 10px;
  text-align: right;
}

.input {
  width: 205px;
}
</style>
